//
//  SleepChartViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/9/22.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "SleepChartViewController.h"
#import "SleepChartView.h"
#import "GetSleepRecordListApi.h"

@interface SleepChartViewController ()

@property(nonatomic,strong) SleepChartView *containerView;
@property(nonatomic,assign) NSInteger weekIndex;
@property(nonatomic,assign) NSInteger monthIndex;

@end

@implementation SleepChartViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    [self didClickRightButton];

}

#pragma mark - 点击事件
- (void)onRightButtonClick:(id)sender
{
    UIImage *screenShot = [OTScreenshotHelper screenshot];
    [ShareView showShareViewWithClickShareBlock:^(ShareType shareType) {
        [DTCSharePlatformManager shareWithImage:screenShot Type:shareType];
    }];
}

-(void)segmentAction:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    NSLog(@"Index %li", (long)Index);
    
    switch (Index) {
            
        case 0:
        {
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getWeekWithIndex:self.weekIndex]];
        }
            break;
        case 1:
        {
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getMonthWithIndex:self.monthIndex]];
        }
            break;
            
        default:
            
            break;
            
    }
    
}

- (void)didClickLeftButton
{
    switch (self.containerView.segmentedControl.selectedSegmentIndex) {
        case 0:
        {
            self.weekIndex -= 1;
            if (self.weekIndex > 0)
            {
                self.weekIndex = 0;
            }
            
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getWeekWithIndex:self.weekIndex]];
        }
            break;
        case 1:
        {
            self.monthIndex -= 1;
            if (self.monthIndex > 0)
            {
                self.monthIndex = 0;
            }
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getMonthWithIndex:self.monthIndex]];
            
        }
            
            break;
            
        default:
            break;
    }
}

- (void)didClickRightButton
{
    switch (self.containerView.segmentedControl.selectedSegmentIndex) {
        case 0:
        {
            self.weekIndex += 1;
            if (self.weekIndex > 0)
            {
                self.weekIndex = 0;
            }
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getWeekWithIndex:self.weekIndex]];
            
        }
            break;
        case 1:
        {
            self.monthIndex += 1;
            if (self.monthIndex > 0)
            {
                self.monthIndex = 0;
            }
            [self getSleepRecordListWithArray:[[BlueToothDataHandle sharedInstance]getMonthWithIndex:self.monthIndex]];
            
            
        }
            
            break;
            
        default:
            break;
    }
}

#pragma mark - 事件处理
- (void)getSleepRecordListWithArray:(NSArray *)dataArray
{
    NSString *startTime = dataArray.firstObject;
    NSString *endTime = dataArray.lastObject;
    NSString *dateString = [NSString stringWithFormat:@"%@.%@-%@.%@",startTime.subString(4,6),startTime.fromIndex(6),endTime.subString(4,6),endTime.fromIndex(6)];
    self.containerView.dateLabel.text = dateString;
    [SVProgressHUD showWithStatus:MyNSLocalizedString(@"正在加载中...")];
    GetSleepRecordListApi *api = [[GetSleepRecordListApi alloc] initWithDic:@{@"device_id":EXRACT_OBJECT(DEVICEID),@"sdate":startTime,@"edate":endTime}];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = [request responseJSONObject];
        if ([dict[@"errcode"] intValue] == 0)
        {
            NSMutableArray *deepSleepArray = [NSMutableArray array];
            NSMutableArray *lightSleepArray = [NSMutableArray array];
            NSInteger deepCount = 0;
            NSInteger lightCount = 0;
            NSArray *data = dict[@"data"];
            
// 取最大值
//            for (int i = 0; i < data.count; i++)
//            {
//                NSInteger step = [data[i][@"step"] intValue];
//                count += step;
//                if (max < step)
//                {
//                    max = step;
//                }
//            }
            
            for (int j = 0; j < dataArray.count; j++)
            {
                // 深睡眠数据
                NSString *dateStr = dataArray[j];
                BOOL hasDeepSleep = NO;
                for (int i = 0; i < data.count; i++)
                {
                    NSInteger step = [data[i][@"deep_sleep"] intValue];
                    if ([data[i][@"date"] isEqualToString:dateStr])
                    {
                        hasDeepSleep = YES;
                        [deepSleepArray addObject:[NSString stringWithFormat:@"%li",(long)step]];
                        break;
                    }
                    else
                    {
                        hasDeepSleep = NO;
                    }
                    deepCount += step;
                }
                if (!hasDeepSleep)
                {
                    [deepSleepArray addObject:@"0"];
                }
                
                // 浅睡眠数据
                BOOL hasLightSleep = NO;
                for (int i = 0; i < data.count; i++)
                {
                    NSInteger step = [data[i][@"light_sleep"] intValue];
                    if ([data[i][@"date"] isEqualToString:dateStr])
                    {
                        hasLightSleep = YES;
                        [lightSleepArray addObject:[NSString stringWithFormat:@"%li",(long)step]];
                        break;
                    }
                    else
                    {
                        hasDeepSleep = NO;
                    }
                    lightCount += step;
                }
                if (!hasLightSleep)
                {
                    [lightSleepArray addObject:@"0"];
                }

            }
            
            if (deepSleepArray.count > 0)
            {
//                [deepSleepArray insertObject:@"" atIndex:0];
//                [lightSleepArray insertObject:@"" atIndex:0];
            }

            if (deepSleepArray.count < 8)
            {
                if (data.count == 0)
                {
                    [self.containerView setData:@[@[],@[]]];
                }
                else
                {
                    [self.containerView setWeekData:@[deepSleepArray,lightSleepArray]];
                }
                self.containerView.countView.dataLabel.text = [NSString stringWithFormat:@"%.1f%@",(float)(deepCount + lightCount)/60/7,MyNSLocalizedString(@"小时")];
                self.containerView.deepView.dataLabel.text = [NSString stringWithFormat:@"%.1f%@",(float)deepCount/60/7,MyNSLocalizedString(@"小时")];
                self.containerView.lightView.dataLabel.text = [NSString stringWithFormat:@"%.1f%@",(float)lightCount/60/7,MyNSLocalizedString(@"小时")];
                self.containerView.countView.hidden = NO;
                self.containerView.lightView.hidden = NO;
                self.containerView.deepView.iconView.hidden = NO;
                self.containerView.deepView.unitLabel.text = MyNSLocalizedString(@"深睡眠");
            }
            else
            {
                self.containerView.countView.hidden = YES;
                self.containerView.lightView.hidden = YES;
                self.containerView.deepView.iconView.hidden = YES;
                self.containerView.deepView.unitLabel.text = MyNSLocalizedString(@"每日平均睡眠");
                self.containerView.deepView.dataLabel.text = [NSString stringWithFormat:@"%.1f%@",(float)deepCount/60/dataArray.count,MyNSLocalizedString(@"小时")];
                if (data.count == 0)
                {
                    [self.containerView setData:@[@[],@[]]];
                }
                else
                {
                    [self.containerView setData:@[deepSleepArray,lightSleepArray]];
                }
            }
        }
        [SVProgressHUD dismiss];
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD showErrorWithStatus:[request responseJSONObject][@"errmsg"]];
    }];
    
    //    [api dtDefaultInterceptStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request)
    //    {
    //
    //    } failure:nil];
}

#pragma mark - 代理


#pragma mark - 通知处理

#pragma mark - 初始化
- (SleepChartView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[SleepChartView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
        [_containerView.leftButton addTarget:self action:@selector(didClickLeftButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.rightButton addTarget:self action:@selector(didClickRightButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}

- (void)setNavigationStyle
{
    [self setNavigationBarTitle:MyNSLocalizedString(@"睡眠统计")];
    [self setRightButtonImage:imageWithName(@"nav_icon_share")];
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.equalTo(superView);
    }];
}

@end
